package com.xinghou.platform.server.api.bussiness.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xinghou.platform.dao.bases.redis.RedisOperator;
import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.entity.req.ListReq;
import com.xinghou.platform.entity.req.ShareInfoReq;
import com.xinghou.platform.entity.req.UserRegistReq;
import com.xinghou.platform.entity.resp.UserInfoResp;
import com.xinghou.platform.lucene.main.UserLuceneService;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.api.bussiness.*;
import com.xinghou.platform.server.api.common.ImageComb;
import com.xinghou.platform.server.api.log.LoggerFactory;
import com.xinghou.platform.server.api.service.StoreLuceneApiService;
import com.xinghou.platform.server.api.service.UserLuceneApiService;
import com.xinghou.platform.server.mq.MqMessage;
import com.xinghou.platform.service.main.NoticeService;
import com.xinghou.platform.service.main.UserService;
import com.xinghou.platform.util.*;
import com.xinghou.platform.util.exception.DBExceptionEnums;
import com.xinghou.platform.util.exception.ServiceException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service("userInfoService")
public class UserInfoBusinessServiceImpl implements UserInfoBusinessService {
    private Logger logInfo = LoggerFactory.getServerInfoLogger(UserInfoBusinessServiceImpl.class);
    @Autowired
    private UserDAO userDAO;

    @Autowired
    private UserRelationScheduleDAO userRelationScheduleDAO;
    @Resource
    private UserLuceneService userLuceneService;

    @Resource
    private UserInviteService userInviteService;

    @Resource
    private ShareInfoBusinessService shareInfoBusinessService;

    @Resource
    private AreaService areaService;
    @Resource
    private UserSignaturesDAO signaturesDAO;

    @Resource
    private InterestTagsDAO interestTagsDAO;
    @Resource
    private UserGeoDAO userGeoDAO;
    @Resource
    private UserStatisticsDAO userStatisticsDAO;
    @Resource
    private UserSignaturesDAO userSignaturesDAO;
    @Resource
    private LoginHistoryDAO loginHistoryDAO;
    @Resource
    private UserService userService;
    @Resource
    private TastInfoBusinessService tastInfoBusinessService;
    @Resource
    private StoreDAO storeDAO;
    @Resource
    private CityDAO cityDAO;
    @Resource
    private VisitToDAO visitToDAO;
    private static  RedisOperator redisOperator;

    @Resource
    private StoreLuceneApiService storeLuceneApiService;
    @Resource
    private MsgInfoBusinessService msgInfoBusinessService;
    @Resource
    private UserRelationFromDAO userRelationFromDAO;
    @Resource
    private UserRelationToDAO userRelationToDAO;
    @Resource
    private DataConfigDAO dataConfigDAO;
    @Resource
    private MqMessage mqMessage;
    @Resource
    private NoticeService noticeService;
    @Resource
    private LoginHistoryService loginHistoryService;
    @Resource
    private UserLuceneApiService userLuceneApiService;
    @Resource
    private UserVisitsDAO userVisitsDAO;

    private String photouri = ConfigUtil.getProperty("file_download");




    public static void  initRedis()
    {
        if(redisOperator==null)
            redisOperator=(RedisOperator) AppContextUtil.getBean("cachedMainRedisOperator");

    }

    public List<UserInfoResp> getUsersSignatures(String ids) {
        List<UserInfoResp> userInfoResps = new ArrayList<UserInfoResp>();
        String[] userids = ids.split(",");
        for (int i = 0; i < ids.length(); i++) {
            UserInfoResp resp = new UserInfoResp();
            UserSignatures userSignatures = userSignaturesDAO.getUserSignatures(Integer.parseInt(userids[i]));
            if(userSignatures==null) continue;;
            resp.setUserid(userSignatures.getUid().toString());
            resp.setSignatures(userSignatures.getSignatures());
           userInfoResps.add(resp);
        }
        return userInfoResps;

    }


    @Override
    public void pubSignatures(UserSignatures signatures) {
        signatures.createtime = System.currentTimeMillis();
        signatures.updatetime = System.currentTimeMillis();
        UserSignatures temp = signaturesDAO.getUserSignatures(signatures.uid);
        if (temp == null)
            signaturesDAO.saveUserSigntures(signatures);
        else
            signaturesDAO.updateUserSigntures(signatures);
    }

    public int createUserAccount(UserRegistReq userRegistReq)
            throws DataAccessException {
        User user = userDAO.getUserByMobile(userRegistReq.getMobile());
        int userid = 0;
        if (user != null) {
            User user1 = getUserBySecondAccount(userRegistReq.getType(), userRegistReq.getSecondaccount());
            if (user1 == null) {
                if (userRegistReq.getType().equals("QQ")) {
                    user.setQqid(userRegistReq.getSecondaccount());
                    user.setQqstate(1);
                } else if (userRegistReq.getType().equals("WB")) {
                    user.setWbid(userRegistReq.getSecondaccount());
                    user.setWbstate(1);
                } else {
                    user.setWxid(userRegistReq.getSecondaccount());
                    user.setWxstate(1);
                }
                userDAO.updateUser(user);
                if (userRegistReq.getType().equals("QQ")) {
                    msgInfoBusinessService.addSystemNote(user.getUserid(), "", 2);
                } else if (userRegistReq.getType().equals("WB")) {
                    msgInfoBusinessService.addSystemNote(user.getUserid(), "", 4);
                } else {
                    msgInfoBusinessService.addSystemNote(user.getUserid(), "", 3);
                }

                userid = user.getUserid();
            } else {
                userid = user.getUserid();
            }
        } else {
            userService.createUserAccount(userRegistReq);
            user = userDAO.getUserByMobile(userRegistReq.getMobile());
            userid = user.getUserid();
            System.out.print("userCreateMessage:" + userid + ",false");
            mqMessage.sendMessageUser(userid + "", false);
        }
        userService.registerHuanxin(user.getUserid(), "123456", "");
        UserLocation_Geo userLocation_Geo = new UserLocation_Geo();
        userLocation_Geo.setUserId(userid);
        return userid;
    }

    @Override
    public UserInfoResp getUserInfo(Integer userid) {
        UserInfoResp userInfoResp = new UserInfoResp();
        User user = userDAO.getUserById(userid);
        if(user==null)
        {
            logInfo.info("userid="+userid+",USER INFO IS NULL");
            return null;
        }
        UserSignatures userSignatures = signaturesDAO.getUserSignatures(user.getUserid());
        userInfoResp.setUserid(user.getUserid() + "");
        userInfoResp.setHeadurl(PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
        userInfoResp.setMobile(user.getPhonenumber());
        userInfoResp.setNickname(user.getNickname());
        userInfoResp.setSex(user.getSex()==null?"":user.getSex().toString());
        userInfoResp.setSignatures(userSignatures==null?"":userSignatures.getSignatures());
        userInfoResp.setAgeyear(user.getAgeyear());
        userInfoResp.setIntr(user.getSignature());
        userInfoResp.setIsreal(user.getIsreal());
        userInfoResp.setTaste(user.getTaste());
        userInfoResp.setTastedesc(getInterestTagsTitleOfUser((user.getTaste())));
        UserStatistics userStatistics=userStatisticsDAO.getUserStatById(user.getUserid());
            userInfoResp.setSharecardcount(userStatistics==null?"0":userStatistics.getSharecount().toString());
        if (userSignatures != null)
            userInfoResp.setSignatures(userSignatures.getSignatures());
        return userInfoResp;
    }

    public String updateUserInfoBase(UserRegistReq userRegist) throws DataAccessException {
        return userService.updateUserInfoBase(userRegist);
    }

    @Override
    public String updateUserInfoTaste(UserRegistReq userRegist) throws DataAccessException {
        return userService.updateUserInfoTaste(userRegist);
    }

    @Override
    public String updateUserPassword(UserRegistReq userRegist) {
        User user = userDAO.getUserByMobile(userRegist.getMobile());
        userDAO.deletePwdCache(user);
        userRegist.setUserid(String.valueOf(user.getUserid()));
        userRegist.setMobile(null);
        return userService.updateUserInfoBase(userRegist);
    }

    @Override
    public String updateUserInfoJob(UserRegistReq userRegist) throws DataAccessException {
        int shopid = -1;

        if (StringUtils.isBlank(userRegist.getShopid())) {
        }
        return userService.updateUserInfoJob(userRegist);
    }

    public String updateUserInfoShop(UserRegistReq userRegist) throws DataAccessException {
        return userService.updateUserInfoShop(userRegist);
    }

    /**
     * 1表示成功   0表示失败
     */
    public String updateUserLocation(UserRegistReq userRegist) {
        Double[] pos = new Double[2];
        if (StringUtils.isNotBlank(userRegist.getLng()) && StringUtils.isNotBlank(userRegist.getLat())) {
            pos[0] = Double.valueOf(userRegist.getLng());
            pos[1] = Double.valueOf(userRegist.getLat());
            UserLocation_Geo userLocation_Geo = new UserLocation_Geo();
            List<City> citylist = new ArrayList<City>();
            userLocation_Geo.setCityCode("");
            if (StringUtils.isNotBlank(userRegist.getCity())) {
                citylist = cityDAO.queryCityListByFullName(userRegist.getCity().split(",")[1]);
                if (citylist.size() > 0)
                    userLocation_Geo.setCityCode(citylist.get(0).getCode());
            }
            userLocation_Geo.setUserType(Integer.valueOf(userDAO.getUserById(Integer.valueOf(userRegist.getUserid())).getUserid()));

            if (userLocation_Geo.getUserType() == 1) {
                userLocation_Geo.setStoreid(Integer.valueOf(userRegist.getShopid()));
            } else
                userLocation_Geo.setStoreid(-1);
            userLocation_Geo.setDeviceId(userRegist.getDeviceID());
            userLocation_Geo.setUserId(Integer.valueOf(userRegist.getUserid()));
            userLocation_Geo.setLastLoginTime(Long.valueOf(DateUtils.getNewZhCNDateTime()));
            userLocation_Geo.setPos(pos);
            User user = userDAO.getUserById(Integer.valueOf(userRegist.getUserid()));
            if (user != null) {
                UserGeo usergeo = userGeoDAO.getUserGeoById(user.getUserid());
                usergeo.setLatitude(Double.valueOf(userRegist.getLat()));
                usergeo.setLongitude(Double.valueOf(userRegist.getLng()));

                if (StringUtils.isNotBlank(userRegist.getCity())) {
                    usergeo.setLocation(userRegist.getCity());
                } else {
                    usergeo.setLocation("");
                }
                usergeo.setGeoHash(GeohashUtil.encodeBin(Double.valueOf(userRegist.getLat()), Double.valueOf(userRegist.getLng()), false));
                usergeo.setGeoLong(GeohashUtil.encodeLong(Double.valueOf(userRegist.getLat()), Double.valueOf(userRegist.getLng())));
                usergeo.setUpdateTime(System.currentTimeMillis());
                userGeoDAO.updateUserGeo(usergeo);
                LoginHistory loginHistory = new LoginHistory();
                loginHistory.setLoginTime(System.currentTimeMillis());
                loginHistory.setUserId(Integer.valueOf(userRegist.getUserid()));
                loginHistory.setLatitude(Double.valueOf(userRegist.getLat()));
                loginHistory.setLongitude(Double.valueOf(userRegist.getLng()));
                loginHistory.setDeviceToken(userRegist.getDeviceID());
                loginHistoryService.saveLoginHistory(loginHistory);
                loginHistory = null;
            }
            return "1";
        } else {
            return "1";
        }

    }


    public String updateUserPwd(UserRegistReq userRegist)
            throws DataAccessException {
        int userid = Integer.parseInt(userRegist.getUserid());
        User user = userDAO.getUserById(userid);
        if (StringUtils.isNotBlank(userRegist.getPwd().toString())) {
            user.setPassword(userRegist.getPwd());
            if (userDAO.updateUser(user) > 0)
                return "0";
            else
                return "1";
        }
        return "1";
    }

    public User getUserBySecondAccount(String type, String account) {
        HashMap map = new HashMap();
        map.put("type", type);
        map.put("account", account);
        return userDAO.getUserBySecondAccountMap(map);
    }

    public User getUserByPassword(String mobile, String password) {
        return userDAO.getUserByPassword(mobile, password);
    }

    //用户登入验证  查询条件手机:mobile 手机号和密码  微信：wechat 只需账号 QQ:qq 只需账号 微博：weibo 只需账号
    //账号：account 只需账号  以及保存用户登入信息
    public UserInfoResp getUserInfo(UserRegistReq userRegistReq)
            throws DataAccessException {
        UserInfoResp userInfoResp = null;
        int userid = -1;
        User user = null;
        HashMap map = new HashMap();
        if("MOBILE".equals(userRegistReq.getType())){
            user = getUserByPassword(userRegistReq.getMobile(), userRegistReq.getPwd());

        }else{
            user = getUserBySecondAccount(userRegistReq.getType(), userRegistReq.getSecondaccount());
        }
        if (user != null) {
            checkclosure(user.getClosuretime());
            userInfoResp=getUserInfo(user.getUserid().toString(),user.getUserid().toString());
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setLoginTime(System.currentTimeMillis());
            loginHistory.setUserId(userid);
            UserStatistics userStatistics = new UserStatistics();
            userStatistics.setStatid(Integer.valueOf(user.getUserid()));
            if (userStatistics != null) {
                userStatistics.setLastlogintime(System.currentTimeMillis());
                userStatisticsDAO.updateUserStat(userStatistics);
            }
            loginHistoryService.saveLoginHistory(loginHistory);
        }

        return userInfoResp;
    }
    @Override
    public User processUserInfoOther(UserRegistReq userRegist)
            throws DataAccessException {
        String account = userRegist.getSecondaccount();
        String type = userRegist.getType();
        String sex = userRegist.getSex();
        String nickname = userRegist.getNickname();
        String headurl = userRegist.getHeadurl();
        if(!StringUtils.isEmpty(sex)&&(!"0".equals(sex)&&!"1".equals(sex)))
        throw new ServiceException(DBExceptionEnums.UNKNOW_SEX);
        HashMap map = new HashMap();
        map.put("type", type);
        map.put("account", account);

        User user = userDAO.getUserBySecondAccountMap(map);
        if(logInfo.isDebugEnabled())
        logInfo.debug("user is null query by account:"+account+",type"+type);
        if (user == null) {
            user = new User();
            user.setCreatetime(System.currentTimeMillis());
            if (type.equals("QQ")) {
                user.setQqid(account);
                user.setNickname(nickname);
                user.setHeadurl(headurl);
                if(!StringUtils.isEmpty(sex))
                    user.setSex(new Short(sex));
                user.setQqstate(1);
            } else if (type.equals("WX")) {
                user.setWxid(account);
                user.setNickname(nickname);
                user.setWxstate(1);
                user.setHeadurl(headurl);
                if(!StringUtils.isEmpty(sex))
                    user.setSex(new Short(sex));
            } else  if (type.equals("SINA")){
                user.setWbid(account);
                user.setNickname(nickname);
                user.setWbstate(1);
                user.setHeadurl(headurl);
                if(!StringUtils.isEmpty(sex))
                    user.setSex(new Short(sex));
            }else if (type.equals("MOBILE")) {
                String phonenumber = userRegist.getMobile();
                user.setPhonenumber(phonenumber);
                user.setPassword(userRegist.getPwd());
                user.setNickname("xh"+phonenumber.substring(phonenumber.length()>4?phonenumber.length()-4:0));
            }
            if(!StringUtils.isEmpty(userRegist.getUasystem())){
                user.setPlatform(Integer.parseInt(userRegist.getUasystem()));
            }

            createNewUser(user);
            createInvite(user.getUserid(),userRegist.getInvitecode());
            userRegist.setTaste("1-11-12");
            userRegist.setUserid(String.valueOf(user.getUserid()));
            updateUserInfoTaste(userRegist);
        }
        return user;
    }

    @Override
    public User processUserMobile(UserRegistReq userRegist)
            throws DataAccessException {
        String account = userRegist.getSecondaccount();
        String type = userRegist.getType();
        String sex = userRegist.getSex();
        String nickname = userRegist.getNickname();
        String headurl = userRegist.getHeadurl();
        if(!StringUtils.isEmpty(sex)&&(!"0".equals(sex)&&!"1".equals(sex)))
            throw new ServiceException(DBExceptionEnums.UNKNOW_SEX);
        User user = new User();
        user.setCreatetime(System.currentTimeMillis());
        if(!StringUtils.isEmpty(userRegist.getUasystem())){
            user.setPlatform(Integer.parseInt(userRegist.getUasystem()));
        }
             if (type.equals("MOBILE")) {
                String phonenumber = userRegist.getMobile();
                user.setPhonenumber(phonenumber);
                user.setPassword(userRegist.getPwd());
                 user.setHeadurl("");
                user.setNickname("xh" + phonenumber.substring(phonenumber.length() > 4 ? phonenumber.length() - 4 : 0));
                 createNewUser(user);
                 createInvite(user.getUserid(),userRegist.getInvitecode());
            }
            userRegist.setUserid(String.valueOf(user.getUserid()));
            userRegist.setTaste("1-11-12");
            updateUserInfoTaste(userRegist);

        return user;
    }

    @Override
    public User createNewUser(User user) {
        user.setSignature("与爱美的女孩做朋友");
        Long nowtime =System.currentTimeMillis();
        user.setUpdatetime(nowtime);
        user.setTaste("1-11-12");
        if(logInfo.isDebugEnabled())
            logInfo.debug("save userinfo:"+ JSON.toJSONString(user));
        int result = userDAO.saveUser(user);
        regUserInfo(user.getUserid());
        UserVisits userVisits = userVisitsDAO.getUserVisitsById(user.getUserid());
        if(userVisits==null){
            userVisitsDAO.addUserVisits(user.getUserid());
        }
        userService.registerHuanxin(user.getUserid(), "123456", user.getNickname());

        UserRelationSchedule  userRelationSchedule= new UserRelationSchedule();
        userRelationSchedule.setUserid(user.getUserid());
        userRelationSchedule.setMax_count(50 + (int) (Math.random() * 20));
        userRelationSchedule.setNow_count(0);
        userRelationSchedule.setNext_time(nowtime + 60 * 60 * 1000 + (int) (Math.random() * 2 * 60 * 60 * 1000));
        userRelationScheduleDAO.insertUserSchedule(userRelationSchedule);

        mqMessage.sendMessageUser(user.getUserid() + "", false);
        return user;
    }

    public void regUserInfo(Integer userid) {
        UserGeo usergeo = new UserGeo();
        usergeo.setGeoId(userid);
        usergeo.setCreateTime(System.currentTimeMillis());
        userGeoDAO.saveUserGeo(usergeo);
        UserSignatures userSignatures=new UserSignatures();
        userSignatures.setUid(userid);
        userSignatures.setSignatures("邂逅爱美的你");
        userSignatures.setCreatetime(System.currentTimeMillis());
        userSignatures.setUpdatetime(System.currentTimeMillis());
        userSignaturesDAO.saveUserSigntures(userSignatures);
        UserStatistics userstat = new UserStatistics();
        userstat.setLogincount(0);
        userstat.setDynamiccount(0);
        userstat.setFanscount(0);
        userstat.setLastlogintime(System.currentTimeMillis());
        userstat.setPraisecount(0);
        userstat.setUpdatetime(System.currentTimeMillis());
        userstat.setAttentioncount(0);
        userstat.setCreatetime(System.currentTimeMillis());
        userstat.setVisitcount(0);
        userstat.setSalecount(0);
        userstat.setBuycount(0);
        userstat.setProductcount(0);
        userstat.setProjectcount(0);
        userstat.setExposurecount(0);
        userstat.setSharecount(0);
        userstat.setStatid(userid);
        userStatisticsDAO.saveUserStat(userstat);
    }


    @Override
    public int updateUserMobile(UserRegistReq userRegist) {
        User user = userDAO.getUserById(Integer.valueOf(userRegist.getUserid()));
        if (StringUtils.isNotBlank(userRegist.getMobile().toString())) {
            user.setPhonenumber(userRegist.getMobile());
            if (userDAO.updateUser(user) > 0)
                return 0;
            else
                return 1;
        }
        return 1;
    }

    @Override
    public int updateSignatures(UserRegistReq userRegist) {
        User user = userDAO.getUserById(Integer.valueOf(userRegist.getUserid()));
        user.setSignature(userRegist.getSignatures());
        System.out.println("updateSignatures:UserId :" + user.getUserid());
        if (userDAO.updateUser(user) > 0)
            return 0;
        else
            return 1;
    }

    public int getUserRelation(Integer userid, Integer touserid) {
        UserRelationFrom userRelationFrom = userRelationFromDAO.getUserRelationFromByUserId(Integer.valueOf(userid), touserid);
        UserRelationTo userRelationTo = userRelationToDAO.getUserRelationToByUserId(Integer.valueOf(userid), touserid);
        int result = 0;
        if (userRelationFrom != null) {
            Short fromlike = userRelationFrom.getIsliked();
            if (fromlike == 1) {
                result = 1;
            }
            if (userRelationTo != null) {
                Short tolike = userRelationTo.getIsliked();
                if (fromlike == 1 && tolike == 1) {
                    result = 2;
                }
            }
        } else {
            if (userRelationTo != null) {
                Short tolike = userRelationTo.getIsliked();
                if (tolike == 1)
                    result = 3;
            }
        }
        return result;

    }
    @Override
    public List<UserInfoResp> searchUsers(UserRegistReq userRegistReq) {
        UserQueryParam userQueryParam=new UserQueryParam();
        if(!StringUtils.isEmpty(userRegistReq.getSex()))
        userQueryParam.sex=Integer.parseInt(userRegistReq.getSex().toString());
        if(!StringUtils.isEmpty(userRegistReq.getMinageyear()))
        userQueryParam.setMinageyear(Integer.parseInt(userRegistReq.getMinageyear()));
        if(!StringUtils.isEmpty(userRegistReq.getMaxageyear()))
        userQueryParam.setMaxageyear(Integer.parseInt(userRegistReq.getMaxageyear()));
        if(!StringUtils.isEmpty(userRegistReq.getHascard()))
        userQueryParam.setHasCard(Integer.parseInt(userRegistReq.getHascard()));
        if(!StringUtils.isEmpty(userRegistReq.getNickname()))
        userQueryParam.setNickname(userRegistReq.getNickname());
        Integer pageno=Integer.parseInt(userRegistReq.getPageno());
        Integer pagesize=Integer.parseInt(userRegistReq.getPagesize());
        Integer fromno=(pageno-1)*pagesize;
        Double distinct=100000000d;
        Double lon=Double.parseDouble(userRegistReq.getLng());
        Double lat=Double.parseDouble(userRegistReq.getLat());
        List<User> users=userLuceneService.queryUserByParams( userQueryParam,fromno,pagesize,distinct,lon,lat);
        List<UserInfoResp> userInfoResps=new ArrayList<UserInfoResp>();
        if(users==null|| users.size()==0)
            return null;
        for(int i=0;i<users.size();i++)
        {
            UserInfoResp userInfoResp=getUserInfo(users.get(i).getUserid());
            if(userInfoResp!=null) {
                userInfoResps.add(userInfoResp);
            }
        }
        return userInfoResps;
    }
    @Override
    public List<UserInfoResp> searchUserByKey(Integer srcuserid, String key, int pageno, int pagesize) {
        int startno = (pageno - 1) * pagesize;
        List<User> users = null;
        List<UserInfoResp> resps = new ArrayList<UserInfoResp>();
        try {
            users = userLuceneApiService.getSearchUserInfos(key, startno, pagesize, null, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (users == null || users.isEmpty()) return null;
        for (int i = 0; i < users.size(); i++) {
            UserInfoResp resp = getUserInfo(srcuserid.toString(), users.get(i).getUserid().toString());
            if (resp != null)
                resps.add(resp);
        }
        return resps;
    }


   /* //发送用户访问消息
    public void noticeUserVisit(String srcuserid,String touserid)
    {
        redisOperator=(RedisOperator)AppContextUtil.getBean("cachedMainRedisOperator");
        String day=DateUtil.getStringDayByDate(new Date());
        String key="key_visit_message:%s,%s,%s,%s";
        int db=6;
        String v=String.format(key,srcuserid,touserid,day,Constants.MESSAGE_VISIT);
        if(redisOperator.exists(v,db))
            return;
        User user=userDAO.getUserById(Integer.parseInt(srcuserid));
        String nickname=user.getNickname();
        Notice notice=new Notice();
        HashMap map=new HashMap();
        map.put("nickname",nickname);
        map.put("headurl",ImageComb.combHeaderUrl(user.getHeadurl()));
        map.put("userid",user.getUserid());
        map.put("messagecode", Constants.MESSAGE_VISIT);
        map.put("type","1");
        String json=JsonUtil.toJson(map);
        notice.setText(json);
        notice.setReceiverId(Integer.parseInt(touserid));
        notice.setPlatform(0);
        noticeService.notice(notice);
        redisOperator.set(v,"1",db);
    }*/


    @Override
    public String getxhh5code(Integer uid) {
        initRedis();
        String a= redisOperator.get("key_adh5code",7);
        return a;
    }

    public void recordVisitInfo(UserRegistReq userRegistReq) {
        if (userRegistReq.getUserid().equals(userRegistReq.getToUserid()))
            return;
        ShareInfoReq req = new ShareInfoReq();
        req.setUserid(userRegistReq.getUserid());
        req.setToUserid(userRegistReq.getToUserid());
        shareInfoBusinessService.saveVisits(req);
        UserVisits userVisits = userVisitsDAO.getUserVisitsById(Integer.parseInt(userRegistReq.getToUserid()));
        if(userVisits==null){
            userVisitsDAO.addUserVisits(Integer.parseInt(userRegistReq.getToUserid()));
            userVisits= new UserVisits();
            userVisits.setUserid(Integer.parseInt(userRegistReq.getToUserid()));
        }
        String visitsStr =  userVisits.getVisits();
        JSONArray array = null;
        if(StringUtils.isBlank(visitsStr)) {
             array =new JSONArray();
        }else{
            array = JSONArray.parseArray(visitsStr);
            array.remove((Object)Integer.parseInt(userRegistReq.getUserid()));
        }
        array.add(0,Integer.parseInt(userRegistReq.getUserid()));
        int size = array.size()>30?30:array.size();
        List  list =array.subList(0,size);
        userVisits.setVisits(list.toString());
        userVisitsDAO.updateUserVisits(userVisits);
        //记录访问记录
       // noticeUserVisit(userRegistReq.getUserid(),userRegistReq.getToUserid());
    }


    public UserInfoResp getUserInfo(String userid, String toUserid) throws DataAccessException {

        int touserid = Integer.valueOf(toUserid);
        UserInfoResp userInfoResp = new UserInfoResp();
        userInfoResp.setUserid(toUserid);
        User user = userDAO.getUserById(touserid);
        if(user==null) {
           /* logInfo.error("userid==========="+userid);
            if(logInfo.isDebugEnabled())
            logInfo.debug("query user return null,userid="+touserid);
            throw new ServiceException(DBExceptionEnums.USER_IS_NULL);*/
            return null;
        }
        if (StringUtils.isEmpty(user.getPassword()))
            userInfoResp.setIsmj(true);
        userInfoResp.setHeadurl(PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
        userInfoResp.setStandheadurl(ImageComb.combHeaderUrl(user.getHeadurl()));
        userInfoResp.setMobile(user.getPhonenumber());
        userInfoResp.setNickname(user.getNickname());
        userInfoResp.setIsreal(user.getIsreal());
        userInfoResp.setSex(user.getSex()==null?"":user.getSex().toString());
        userInfoResp.setAgeyear(user.getAgeyear());
        userInfoResp.setMobile(user.getPhonenumber());
            userInfoResp.setIntr(user.getSignature());
        UserSignatures signatures = userSignaturesDAO.getUserSignatures(user.getUserid());
        if (signatures != null)
            userInfoResp.setSignatures(signatures.getSignatures());
        if (!user.equals(toUserid)) {
            int result = getUserRelation(Integer.parseInt(userid), touserid);
            userInfoResp.setIsfollow(result + "");
        }
        if (StringUtils.isNotBlank(user.getQqid())) {
            userInfoResp.setQq(user.getQqid());
        }
        if (StringUtils.isNotBlank(user.getWbid())) {
            userInfoResp.setWeibo(user.getWbid());
        }
        if (StringUtils.isNotBlank(user.getWxid())) {
            userInfoResp.setWechat(user.getWxid());
        }
        userInfoResp.setTaste(user.getTaste());
        userInfoResp.setTastedesc(getInterestTagsTitleOfUser(user.getTaste()));
        String[] v = areaService.getAreaCodeForApp(user.getAdcode());
        if (v != null) {
            userInfoResp.setArea(v[0]);
            userInfoResp.setAreadesc(v[1]);
        }
        //统计数量
        UserStatistics userStatistics = userStatisticsDAO.getUserStatById(user.getUserid());
        if (userStatistics != null) {
            userInfoResp.setSharecardcount(userStatistics.getSharecount().toString());
            userInfoResp.setFanscount(userStatistics.getFanscount().toString());
            userInfoResp.setFollowcount(userStatistics.getAttentioncount().toString());
            userInfoResp.setLastlogintime(String.valueOf(userStatistics.getLastlogintime()));
            userInfoResp.setCreatetime(String.valueOf(userStatistics.getCreatetime()));
        }
        return userInfoResp;
    }

    /**
     * 获取用户兴趣列表
     *
     * @return
     */
    public String getInterestTagsTitleOfUser(String taste) {
        String taglist = "";
        if (StringUtils.isEmpty(taste)) return null;
        List<InterestTags> interestTags = new ArrayList<InterestTags>();
        String[] tagids = taste.split("-");
        for (int i = 0; i < tagids.length; i++) {
            taglist = taglist + dataConfigDAO.getDataConfigByTag_id(Integer.parseInt(tagids[i]), 1).getName();
            if (i != tagids.length - 1)
                taglist = taglist + "-";
        }
        return taglist;
    }

    public String distanceUserAndUser(String userid, String touserid) {

        UserGeo userGeo = userGeoDAO.getUserGeoById(Integer.valueOf(userid));
        Double[] pos = new Double[2];
        if (userGeo != null) {
            if (userGeo.getLongitude() != null && userGeo.getLatitude() != null) {
                pos[0] = userGeo.getLongitude();
                pos[1] = userGeo.getLatitude();
            }
        }
        UserGeo userGeo1 = userGeoDAO.getUserGeoById(Integer.valueOf(touserid));
        Double[] pos1 = new Double[2];
        if (userGeo1 != null) {
            if (userGeo1.getLongitude() != null && userGeo1.getLatitude() != null) {
                pos1[0] = userGeo1.getLongitude();
                pos1[1] = userGeo1.getLatitude();
            }
        }

        return GeohashUtil.distanceOfTwoPointsTOString(pos[0], pos[1], pos1[0], pos1[1], GeohashUtil.GaussSphere.Beijing54);

    }

    //修改手艺人擅长风格，入行时间等
    @Override
    public int updateUserStyle(UserRegistReq userRegistReq) {
        User user = userDAO.getUserById(Integer.parseInt(userRegistReq.getUserid()));
        if (user != null) {
            if (user.getUserid().toString().equals(userRegistReq.getUserid())) {

                return userDAO.updateUser(user);
            }
        }
        return 0;
    }

    @Override
    public int mobileExist(String phonenumber, String type, String secondaccount) {
        User user = userDAO.getUserByMobile(phonenumber);
        if (user != null) {
            //throw new ServiceException(DBExceptionEnums.MOBILE_IS_ALREADY_EXIT);
        }
        if (user == null) {
            return 1;
        } else {
            int result = 0;
            if (null != secondaccount && null != type) {
                if (type.equals("WB")) {
                    if (user.getWbstate() > 0) {
                        result = 1;
                    }
                } else if (type.equals("WX")) {
                    if (user.getWxstate() > 0) {
                        result = 1;
                    }
                } else if (type.equals("QQ")) {
                    if (user.getQqstate() > 0) {
                        result = 1;
                    }
                }
                if (result == 0) {
                    User user2 = getUserBySecondAccount(type, secondaccount);
                    if (null != user2) {
                        result = 2;
                    }
                }
            }
            return result;
        }
    }

    @Override
    public List<UserInfoResp> getFollowUsers(Integer userid, Integer pageno, Integer pagesize) {
        Integer startno = (pageno - 1) * pagesize;
        List<UserRelationFrom> userRelationFroms = userRelationFromDAO.getUserRelationFromByToUserId(userid, startno, pagesize);
        if (userRelationFroms == null || userRelationFroms.isEmpty())
            return null;
        List<UserInfoResp> userInfos = new ArrayList<UserInfoResp>();
        for (int i = 0; i < userRelationFroms.size(); i++) {
            UserInfoResp resp = getUserInfo(userRelationFroms.get(i).getTouserid());
            if(resp==null) continue;
            resp.setTastedesc(getInterestTagsTitleOfUser((resp.getTaste())));
            UserStatistics userStatistics = userStatisticsDAO.getUserStatById(Integer.parseInt(resp.getUserid()));
            if (userStatistics != null)
                resp.setSharecardcount(userStatistics.getSharecount().toString());
            userInfos.add(resp);
        }
        return userInfos;
    }

    @Override
    public List<UserInfoResp> getFanUsers(Integer userid, Integer pageno, Integer pagesize) {
        Integer startno = (pageno - 1) * pagesize;
        List<UserRelationTo> userRelationTos = userRelationToDAO.getUserRelationToByToUserId(userid, startno, pagesize);
        if (userRelationTos == null || userRelationTos.isEmpty())
            return null;
        List<UserInfoResp> userInfos = new ArrayList<UserInfoResp>();
        for (int i = 0; i < userRelationTos.size(); i++) {
            UserInfoResp resp = getUserInfo(userRelationTos.get(i).getFromuserid());
            if(resp==null) continue;
            resp.setTastedesc(getInterestTagsTitleOfUser(resp.getTaste()));
            UserStatistics userStatistics = userStatisticsDAO.getUserStatById(Integer.parseInt(resp.getUserid()));
            if (userStatistics != null)
                resp.setSharecardcount(userStatistics.getAttentioncount().toString());
            userInfos.add(resp);
        }
        return userInfos;
    }

    @Override
    public void saveHistoryLog(LoginHistory history) {
        loginHistoryService.saveLoginHistory(history);

    }

    @Override
    public User getUser(Integer uid) {
        return userDAO.getUserById(uid);
    }
    @Override
    public String getRandomUser(int sex) {
        int scope= 500+ (int)(Math.random()*5000000);
        String uid= userDAO.getRandomUser(scope,sex);
        if(StringUtils.isBlank(uid)){
            uid ="";
        }
        return uid;
    }
    @Override
    public List<UserInfoResp>  userList(ListReq listReq){
        return  userDAO.userList(listReq);
    }

    @Override
    public void closureUser(ListReq listReq){
        if(listReq.getClosuretype().equals("1")){
            listReq.setClosuretime(String.valueOf(DateUtil.addSevenDay()));
        }else if(listReq.getClosuretype().equals("2")) {
            listReq.setClosuretime("1");
        }
        User user = userDAO.getUserById(Integer.parseInt(listReq.getUserid()));
        user.setClosurereason(listReq.getClosurereason());
        user.setClosuretime(listReq.getClosuretime());
        user.setOperator(listReq.getOperator());
        user.setOperatetime(System.currentTimeMillis());
        userDAO.updateUser(user);
    }

    @Override
    public void unclosureUser(ListReq listReq){
        User user = userDAO.getUserById(Integer.parseInt(listReq.getUserid()));
        user.setClosuretime("");
        user.setOperator(listReq.getOperator());
        userDAO.updateUser(user);
    }

    @Override
    public int getCheckMobileCount(String mobile){
         return userDAO.getCheckMobileCount(mobile);
    }

    @Override
    public Boolean isMobileBind(String mobile) {
        int count=userDAO.getMobileCount(mobile);
        if(count>0)
            return true;
        else return  false;
    }

    private void checkclosure(String closuretime) {
        if(!StringUtils.isBlank(closuretime)){
            if("1".equals(closuretime)){
                throw new ServiceException(DBExceptionEnums.FOREVER_CLOSURE);
            }else if(Long.parseLong(closuretime)>System.currentTimeMillis()){
                throw new ServiceException(DBExceptionEnums.SEVERN_CLOSURE);
            }
        }
    }
    @Override
    public void checkclosureByUserId(String userid) {
        User user = userDAO.getUserById(Integer.parseInt(userid));
        if(user==null){
            return;
        }
       String closuretime= user.getClosuretime();
        if(!StringUtils.isBlank(closuretime)){
            if("1".equals(closuretime)){
                throw new ServiceException(DBExceptionEnums.FOREVER_CLOSURE);
            }else if(Long.parseLong(closuretime)>System.currentTimeMillis()){
                throw new ServiceException(DBExceptionEnums.SEVERN_CLOSURE);
            }
        }
    }
    public List<UserInfoResp> getHeadAndNameById(String ids) throws DataAccessException {
        List<UserInfoResp> list = new ArrayList<>();
        String[] idArray = ids.split(",");
        if(null==idArray||idArray.length==0){
            return  list;
        }
        for(int i =0;i<idArray.length;i++){
            UserInfoResp userInfoResp = new UserInfoResp();
            User user = userDAO.getUserById(Integer.parseInt(idArray[i]));
            if(user!=null){
                userInfoResp.setUserid(String.valueOf(user.getUserid()));
                userInfoResp.setNickname(user.getNickname());
                userInfoResp.setHeadurl(PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
            }
            list.add(userInfoResp);
        }

        return list;
    }

    public void createInvite(Integer userid,String inviteCode){
       if(StringUtils.isEmpty(inviteCode))
            return;
        Integer userId = userInviteService.getUserByInviteCode(inviteCode);
        User inviteuser = userDAO.getUserById(userId);
        if(null ==inviteuser)
            return;
        UserInvite userInvite = new UserInvite();
        userInvite.setUid(userid);
        userInvite.setInviteuid(inviteuser.getUserid());
        userInvite.setCreatetime(System.currentTimeMillis());
        userInviteService.addUserInvite(userInvite);


    }

    @Override
    public List<String> getLastThreeDayData(){
        List<String> list = new ArrayList<String>();
        Long today = DateUtil.getDayBegin();
        Long yestoday = today-60*60*24*1000;
        Long lasttwoday = yestoday-60*60*24*1000;
        Long lastthreeday = lasttwoday-60*60*24*1000;
        DateCount dc = new DateCount();

        long yestodaywx =userDAO.getUserDateCountByWX(today, yestoday);
        long yestodayqq =userDAO.getUserDateCountByQQ( today, yestoday);
        long yestodaywb =userDAO.getUserDateCountByWB( today, yestoday);
        long yestodayall =userDAO.getUserDateCountAll(today, yestoday);
        String yestodayCount = "昨天数据 微信:"+ yestodaywx+",qq:"+yestodayqq+",微博:"+yestodaywb+",总:"+yestodayall;
        list.add(yestodayCount);
        long lasttwodaywx = userDAO.getUserDateCountByWX( yestoday, lasttwoday);
        long lasttwodayqq = userDAO.getUserDateCountByQQ( yestoday, lasttwoday);
        long lasttwodaywb = userDAO.getUserDateCountByWB( yestoday, lasttwoday);
        long lasttwodayall =userDAO.getUserDateCountAll( yestoday, lasttwoday);
        String lasttwodayCount = "前天数据 微信:"+ lasttwodaywx+",qq:"+lasttwodayqq+",微博:"+lasttwodaywb+",总:"+lasttwodayall;
        list.add(lasttwodayCount);
        long lastthreedaywx = userDAO.getUserDateCountByWX( lasttwoday, lastthreeday);
        long lastthreedayqq = userDAO.getUserDateCountByQQ( lasttwoday, lastthreeday);
        long lastthreedaywb = userDAO.getUserDateCountByWB( lasttwoday,lastthreeday);
        long lastthreedayall = userDAO.getUserDateCountAll( lasttwoday, lastthreeday);
        String lastthreedayCount = "大前天数据 微信:"+ lastthreedaywx+",qq:"+lastthreedayqq+",微博:"+lastthreedaywb+",总:"+lastthreedayall;
        list.add(lastthreedayCount);
        return  list;
    }


}
